package com.arch.flink.biz.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 *
 * value_state 案例
 *
 * @author pizhihui
 * @date 2020-07-30
 */
public class WordCountParaToolDemo {

    private static FlatMapFunction<String, WordAndOne> STRING_SPLIT_ONE = (s, collector) -> {
        String[] s1 = s.split(" ");
        for (String s2 : s1) {
            collector.collect(new WordAndOne(s2, 1));

        }
    };

    private static class SplitClass implements FlatMapFunction<String, WordAndOne> {

        @Override
        public void flatMap(String s, Collector<WordAndOne> out) throws Exception {
            String[] s1 = s.split(" ");
            for (String s2 : s1) {
                out.collect(new WordAndOne(s2, 1));
            }
        }
    }

    public static void main(String[] args) throws Exception {

        ParameterTool parameterTool = ParameterTool.fromArgs(args);
        String host = parameterTool.get("hostname", "localhost");
        int port = parameterTool.getInt("port", 7777);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        DataStreamSource<String> ds = env.socketTextStream(host, port);

        SingleOutputStreamOperator<WordAndOne> so = ds
                .flatMap(new SplitClass())
                .keyBy("word")
                .sum("num");

        so.print();

        env.execute("wordcount demo");

    }

}
